// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: The CoAP endpoint realization.

#include "baidu_ca_coap_ep.h"

BCA_INT_IMPL bca_coap_ep_ptr bca_coap_ep_create(const char* name,
        const char* type, bca_u32_t lifetime, const bca_addr_t* addr) {
    bca_coap_ep_ptr ptr = BCA_MALLOC(sizeof(bca_coap_ep_t));

    if (ptr) {
        bca_size_t len;
        BCA_MEMSET(ptr, 0, sizeof(bca_coap_ep_t));

        if (name && (len = BCA_STRLEN(name)) > 0) {
            if ((ptr->name_ptr = BCA_MALLOC(len)) == NULL) {
                goto error;
            }

            BCA_MEMCPY(ptr->name_ptr, name, len);
            ptr->name_len = len;
        }

        if (type && (len = BCA_STRLEN(type)) > 0) {
            if ((ptr->type_ptr = BCA_MALLOC(len)) == NULL) {
                goto error;
            }

            BCA_MEMCPY(ptr->type_ptr, type, len);
            ptr->type_len = len;
        }

        if ((ptr->lifetime_ptr = BCA_MALLOC(LIFETIME_MAX_LEN)) == NULL) {
            goto error;
        }

        ptr->lifetime_len = BCA_SNPRINTF(ptr->lifetime_ptr, LIFETIME_MAX_LEN, "%d",
                                         lifetime);

        if (addr) {
            if ((ptr->address = BCA_MALLOC(sizeof(bca_addr_t))) == NULL) {
                goto error;
            }

            BCA_MEMCPY(ptr->address, addr, sizeof(bca_addr_t));

            if (addr->host) {
                ptr->address->host = BCA_MALLOC(addr->host_size);
                BCA_MEMCPY(ptr->address->host, addr->host, addr->host_size);
            }
        }
    }

exit:
    return ptr;
error:
    bca_coap_ep_destroy(ptr);
    ptr = NULL;
    goto exit;
}

BCA_INT_IMPL bca_status_t bca_coap_ep_destroy(bca_coap_ep_ptr ptr) {
    if (ptr) {
        if (ptr->name_ptr) {
            BCA_FREE(ptr->name_ptr);
        }

        if (ptr->type_ptr) {
            BCA_FREE(ptr->type_ptr);
        }

        if (ptr->lifetime_ptr) {
            BCA_FREE(ptr->lifetime_ptr);
        }

        if (ptr->address) {
            if (ptr->address->host) {
                BCA_FREE(ptr->address->host);
            }

            BCA_FREE(ptr->address);
        }

        BCA_FREE(ptr);
    }

    return BCA_NO_ERR;
}
